<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { omit } from 'lodash-es'
import { menuConfig } from './config'
import { addMenu, deleteMenu, getMenu, updateMenu } from '@/api/system'
import PageFormTable from '@/components/page/BaseFormTable/index.vue'
import { useFetch } from '@/composables/useFetch'

const PageFormTableRef = ref<InstanceType<typeof PageFormTable>>()

const apiConfig = {
  getTableList: getMenu,
  addTableItem: addMenu,
  updateTableItem: updateMenu,
  deleteTableItem: deleteMenu,
  _handleEditModel,
}

// 页面请求
const { data: menuResult, execute: getMenuListExecute } = useFetch((parmas: any) => getMenu(parmas))

function _handleEditModel(data: any) {
  const editData = omit(data, ['createTime', 'updateTime'])
  return editData
}

const initMenuConfig = ref(menuConfig)
async function getMenuList(params?: any) {
  await getMenuListExecute(params)
  const children = menuResult.value!.data.map((item: any) => {
    return {
      type: 'select-option',
      label: item.name,
      value: item.id,
    }
  })
  children.unshift({
    type: 'select-option',
    label: 'ROOT',
    value: 0,
  })
  initMenuConfig.value.options = menuConfig.options.map((item: any) => {
    if (item.prop === 'pid') {
      return {
        ...item,
        children,
      }
    }
    return item
  })
}

onMounted(() => {
  getMenuList()
})

watch(() => PageFormTableRef.value?.visible, (nVal: any) => {
  if (nVal)
    getMenuList()
})
</script>

<template>
  <PageFormTable
    ref="PageFormTableRef"
    :config="initMenuConfig"
    :api-config="apiConfig"
  >
    <template #customs="{ column, record }">
      <template v-if="column.dataIndex === 'action'">
        <div class="gp__flex-start">
          <a-button class="gp__plain-btn" @click.stop="PageFormTableRef?.onClickEditForm({ ...record })">
            {{ menuConfig.text.editAction }}
          </a-button>
          <a-popconfirm
            title="Are you sure delete this menu?"
            cancel-text="No"
          >
            <template #okButton>
              <a-button type="primary" size="small" :loading="PageFormTableRef?.deleteLoading" @click="PageFormTableRef?.onClickDeleteAction({ id: record.id })">
                Yes
              </a-button>
            </template>
            <a-button danger @click.stop>
              Delete
            </a-button>
          </a-popconfirm>
        </div>
      </template>
    </template>
  </PageFormTable>
</template>
